<?php
declare (strict_types = 1);

namespace app\middleware;

use Firebase\JWT\JWT;

class Check
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token=$request->header('Authorization');
        if(empty($token)){
            $token = $request->request('token');
        }

        //判断用户token是否过期或者是否非法
        if (empty($token)) {
            return json(['code' => 401, 'msg' => 'AccessToken is empty']);
        }

        try {
            //判断token是否为非法的token
            $key = config('system.tokenKey');
            try {
                $token_arr = (array)JWT::decode($token, $key, array('HS256'));
            } catch (\UnexpectedValueException $exception) {
                return json(['code' => 401, 'msg' => 'Invalid AccessToken']);
            }
            if (empty($token_arr)) {
                return json(['code' => 401, 'msg' => 'Invalid AccessToken']);
            } else {
                //判断token是否非法的
                if (isset($token_arr['user_id']) && isset($token_arr['expire_time'])) {
                    if (!empty($token_arr['user_id']) && !empty($token_arr['expire_time'])) {
                        //判断时间是否过期
                        if(time() <= $token_arr['expire_time']) {
                            define('UID',$token_arr['user_id']);
                            return $next($request);
                        }else{
                            //提醒登录过去
                            return json(['code'=>402,'msg'=>'Login expired']);
                        }
                    } else {
                        return json(['code' => 401, 'msg' => 'Invalid AccessToken']);
                    }
                } else {
                    return json(['code' => 401, 'msg' => 'Invalid AccessToken']);
                }
            }
        } catch (\Exception $exception) {
            return json(['code'=>500,'msg'=>$exception->getMessage()]);
        }
    }
}
